import { Application, HttpClientResponse } from "egg";
import CodoBase from "../../CodoBase";
import { hikvision } from "./type";
import CodoError from "../../CodoError";
import { HttpClientResponse as HttpClientResponseOld } from "urllib";

const symbolToken = Symbol("accessToken");

export class HikvisionBaseService extends CodoBase {
	constructor(app: Application, public config: hikvision.isc.ISCConfig) {
		super(app);
	}

	protected get accessToken() {
		if (!this[symbolToken]) throw new CodoError(`Access Token is not set.`);
		return this[symbolToken] as string;
	}

	setAccessToken(accessToken: string) {
		this[symbolToken] = accessToken;
		return this;
	}

	handleResponseException(
		res: HttpClientResponse<hikvision.isc.IResponse> | HttpClientResponseOld<hikvision.isc.IResponse>,
		errmsg: string = "-"
	) {
		// @ts-ignore
		const url = res.res?.requestUrls?.[0] || (res as any).url;
		if (res.status !== 200) {
			throw new CodoError(`hikvision 请求出错 %s\r\n %s`, url, errmsg);
		}
		if (res.data.code != "0") {
			throw new CodoError(`hikvision 业务异常 %s\r\n %s\r\n %s\r\n %s`, url, errmsg, res.data.code, res.data.msg);
		}
	}
}
